<?php

require_once __DIR__ . '/vendor/autoload.php';

$app = require_once __DIR__ . '/bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

echo "🔍 调试认证问题\n";
echo "================\n\n";

// 1. 检查用户数据
echo "1️⃣ 检查用户数据...\n";
$users = \DB::table('users')->get();
if ($users->count() === 0) {
    echo "❌ 没有用户数据！\n";

    // 创建测试用户
    $userId = \DB::table('users')->insertGetId([
        'username' => 'admin',
        'phone' => '13800000000',
        'password' => \Illuminate\Support\Facades\Hash::make('123456'),
        'status' => 'active',
        'created_at' => now(),
        'updated_at' => now(),
    ]);
    echo "✅ 创建测试用户 ID: $userId\n";
} else {
    echo "✅ 找到 " . $users->count() . " 个用户\n";
    foreach ($users as $user) {
        echo "   - 用户: {$user->username}, 状态: {$user->status}\n";
    }
}

// 2. 检查角色数据
echo "\n2️⃣ 检查角色数据...\n";
$roles = \DB::table('roles')->get();
if ($roles->count() === 0) {
    echo "❌ 没有角色数据！\n";

    // 创建管理员角色
    $roleId = \DB::table('roles')->insertGetId([
        'name' => '系统管理员',
        'code' => 'admin',
        'description' => '系统管理员',
        'type' => 'system',
        'status' => 'active',
        'permissions' => json_encode(['*']), // 所有权限
        'created_at' => now(),
        'updated_at' => now(),
    ]);
    echo "✅ 创建管理员角色 ID: $roleId\n";
} else {
    echo "✅ 找到 " . $roles->count() . " 个角色\n";
    foreach ($roles as $role) {
        echo "   - 角色: {$role->name}, 权限: " . substr($role->permissions, 0, 50) . "...\n";
    }
}

// 3. 检查用户角色关联
echo "\n3️⃣ 检查用户角色关联...\n";
$userRoles = \DB::table('user_roles')->get();
if ($userRoles->count() === 0) {
    echo "❌ 没有用户角色关联数据！\n";

    // 创建关联
    if ($users->count() > 0 && $roles->count() > 0) {
        \DB::table('user_roles')->insert([
            'user_id' => $users->first()->id,
            'role_id' => $roles->first()->id,
            'start_date' => now()->format('Y-m-d'),
            'status' => 'active',
            'reason' => '系统初始化',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
        echo "✅ 创建用户角色关联\n";
    }
} else {
    echo "✅ 找到 " . $userRoles->count() . " 个用户角色关联\n";
}

// 4. 测试认证流程
echo "\n4️⃣ 测试认证流程...\n";

$kernel = $app->make('Illuminate\Contracts\Http\Kernel');

// 4.1 测试登录
echo "   测试登录...\n";
$loginRequest = \Illuminate\Http\Request::create('/api/auth/login', 'POST', [], [], [], [
    'HTTP_Accept' => 'application/json',
    'CONTENT_TYPE' => 'application/json'
]);
$loginRequest->merge(['username' => 'admin', 'password' => '123456']);

$loginResponse = $kernel->handle($loginRequest);
$loginData = json_decode($loginResponse->getContent(), true);

if ($loginResponse->getStatusCode() === 200 && isset($loginData['data']['token'])) {
    $token = $loginData['data']['token'];
    echo "   ✅ 登录成功，获得token: " . substr($token, 0, 20) . "...\n";

    // 4.2 测试me接口
    echo "   测试me接口...\n";
    $meRequest = \Illuminate\Http\Request::create('/api/auth/me', 'GET', [], [], [], [
        'HTTP_Authorization' => 'Bearer ' . $token,
        'HTTP_Accept' => 'application/json'
    ]);

    $meResponse = $kernel->handle($meRequest);
    $meData = json_decode($meResponse->getContent(), true);

    if ($meResponse->getStatusCode() === 200) {
        echo "   ✅ me接口正常\n";
    } else {
        echo "   ❌ me接口异常: " . $meResponse->getStatusCode() . "\n";
        echo "   响应: " . $meResponse->getContent() . "\n";
    }

    // 4.3 测试用户列表
    echo "   测试用户列表...\n";
    $usersRequest = \Illuminate\Http\Request::create('/api/users', 'GET', [], [], [], [
        'HTTP_Authorization' => 'Bearer ' . $token,
        'HTTP_Accept' => 'application/json'
    ]);

    $usersResponse = $kernel->handle($usersRequest);
    if ($usersResponse->getStatusCode() === 200) {
        echo "   ✅ 用户列表正常\n";
    } else {
        echo "   ❌ 用户列表异常: " . $usersResponse->getStatusCode() . "\n";
        echo "   响应: " . $usersResponse->getContent() . "\n";
    }

} else {
    echo "   ❌ 登录失败: " . $loginResponse->getContent() . "\n";
}

// 5. 检查路由
echo "\n5️⃣ 检查路由配置...\n";
try {
    $routes = app('router')->getRoutes();
    $apiRoutes = [];

    foreach ($routes as $route) {
        if (str_starts_with($route->uri(), 'api/')) {
            $apiRoutes[] = $route->uri();
        }
    }

    $checkRoutes = [
        'api/auth/login' => '登录路由',
        'api/auth/me' => '用户信息路由',
        'api/users' => '用户列表路由',
        'api/roles' => '角色路由',
        'api/menus' => '菜单路由'
    ];

    foreach ($checkRoutes as $routePath => $description) {
        $found = false;
        foreach ($apiRoutes as $apiRoute) {
            if (str_contains($apiRoute, $routePath)) {
                $found = true;
                break;
            }
        }

        if ($found) {
            echo "   ✅ {$description} 已配置\n";
        } else {
            echo "   ❌ {$description} 未配置\n";
        }
    }
} catch (Exception $e) {
    echo "   ⚠️ 路由检查失败: " . $e->getMessage() . "\n";
}

echo "\n🎯 调试完成！\n";

?>
